<?php
declare (strict_types=1);

namespace app\circle\logic;

use app\circle\model\Like as LikeModel;
use app\common\exception\LogicException;
use Exception;

/**
 * 点赞逻辑层
 */
class Like extends LikeModel
{

    /**
     * 点赞/取消点赞
     * Author 亓官雨树<lucky.max@foxmail.com>
     * Date 2021-05-14
     *
     * @param array $param [description]
     * @return void [type]        [description]
     * @throws Exception
     */
    public function like(array $param)
    {
        // 验证数据
        $this->getValidate()->scene('like')->failException()->check($param);
        // 参数
        $mid    = request()->mid;
        $type   = $param['type'];
        $obj_id = $param['obj_id'];
        $cache  = 'circle_like_' . $type . '_' . $mid;
        // 检查频繁操作，5秒
        if (cache($cache)) throw new LogicException('操作频繁，请稍后重试');
        // 缓存当前操作
        cache($cache, 1, 5);
        //
        $exist = $this->withTrashed()->where('type', $type)->whereUserId($mid)->whereObjId($obj_id)->findOrEmpty();

        $this->startTrans();
        try {
            $mod = $type == 2 ? app(Comment::class) : app(Circle::class);
            $obj = $mod->findOrEmpty($obj_id);

            $add = 1;

            switch ($param['status']) {
                case 1:
                    if ($exist->isEmpty()) {
                        $param['user_id'] = $mid;
                        $create           = $this::create($param);
                        if ($create->isEmpty()) throw new LogicException("操作失败");
                    } else {
                        if ($exist->delete_time) {
                            if (!$exist->restore()) throw new LogicException("操作失败");
                        } else {
                            $add = 0;
                        }

                    }
                    $obj->like_num += $add;
                    break;

                default:
                    if (!$exist->isEmpty() && !$exist->delete_time) {
                        if (!$exist->delete()) throw new LogicException("操作失败");
                    } else {
                        $add = 0;
                    }

                    $obj->like_num -= $add;
                    break;
            }

            if (!$obj->save()) throw new LogicException("操作失败");

            $this->commit();
        } catch (LogicException|Exception $e) {
            $this->rollback();
            throw new LogicException($e->getMessage());
        }

    }
}
